//
//  YYHomeView.m
//  CollarMicrophone
//
//  Created by Yown on 2024/3/20.
//

#import "YYHomeView.h"
#import "YYDeviceOtherStateView.h"
#import "YYDeviceConnectedView.h"
#import "YYNameSilderView.h"
#import "YYSoundCell.h"

#import <BIToolModule/BIWaterfallLayout.h>
#import <BIToolModule/BIProjectDefine.h>
#import <BIProjectModule/BIAppDefine.h>
#import <BIToolModule/NSArray+Helper.h>
#import <BIToolModule/NSObject+HUD.h>
#import <BIToolModule/BIAlertAction.h>

#import <Masonry/Masonry.h>

@interface YYHomeView () <UICollectionViewDelegate, UICollectionViewDataSource, BIWaterfallLayoutDelegate>

@property (nonatomic) YYHomeModel *homeModel;

/// 整体容器
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *contentView;

/// 设备UI
@property (weak, nonatomic) IBOutlet UIView *deviceView;
/// 连接成功的设备view
@property (nonatomic) YYDeviceConnectedView *deviceConnectedView;
/// 未连接和连接中的设备view
@property (nonatomic) YYDeviceOtherStateView *deviceOtherStateView;

/// 音量UI
@property (weak, nonatomic) IBOutlet UIView *volumeView;
/// 话筒音量
@property (nonatomic) YYNameSilderView *micVolSliderView;
/// 监听音量
@property (nonatomic) YYNameSilderView *monitorVolSliderView;
/// 混响大小
@property (nonatomic) YYNameSilderView *reverbVolSliderView;
/// 降噪等级
@property (nonatomic) YYNameSilderView *noiseReductionLevelSliderView;
/// 平直
@property (weak, nonatomic) IBOutlet UIButton *straightnessButton;
@property (weak, nonatomic) IBOutlet UILabel *straightnessLabel;
/// 低音增强
@property (weak, nonatomic) IBOutlet UIButton *bassButton;
@property (weak, nonatomic) IBOutlet UILabel *bassLabel;
/// 中音增强
@property (weak, nonatomic) IBOutlet UIButton *baritoneButton;
@property (weak, nonatomic) IBOutlet UILabel *baritoneLabel;
/// 高音增强
@property (weak, nonatomic) IBOutlet UIButton *trebleButton;
@property (weak, nonatomic) IBOutlet UILabel *trebleLabel;

/// 声音UI
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

/// 其他UI
@property (weak, nonatomic) IBOutlet UIView *otherView;
/// 闪避
@property (weak, nonatomic) IBOutlet UILabel *dodgeLabel;
@property (weak, nonatomic) IBOutlet UIButton *dodgeButton;
/// 音响模式
@property (weak, nonatomic) IBOutlet UILabel *audioModeLabel;
@property (weak, nonatomic) IBOutlet UIButton *audioModeButton;

@end

@implementation YYHomeView

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupViews];
    [self setupLayout];
}

- (void)setupViews {
    self.backgroundColor = [UIColor loadColorFromString:@"#F4F4F4"];
    
    self.scrollView.backgroundColor = [UIColor clearColor];
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    self.contentView.backgroundColor = [UIColor clearColor];
    
    [self setupDeviceStateView];
    [self setupVolumeView];
    [self setupSoundView];
    [self setupOther];
}

- (void)setupDeviceStateView {
    self.deviceView.layer.masksToBounds = YES;
    self.deviceView.layer.cornerRadius = 16;
    self.deviceView.backgroundColor = [UIColor whiteColor];
    
    self.deviceConnectedView = [YYDeviceConnectedView view];
    @weakify(self);
    self.deviceConnectedView.clickDisconnectButtonBlock = ^{
        @strongify(self);
    };
    [self.deviceConnectedView reloadDeviceState:kBIBluetoothDisconnected];
    [self.deviceView addSubview:self.deviceConnectedView];
    
    self.deviceOtherStateView = [YYDeviceOtherStateView view];
    [self.deviceOtherStateView reloadDeviceState:kBIBluetoothDisconnected];
    [self.deviceView addSubview:self.deviceOtherStateView];
}

- (void)setupVolumeView {
    self.volumeView.layer.masksToBounds = YES;
    self.volumeView.layer.cornerRadius = 16;
    self.volumeView.backgroundColor = [UIColor whiteColor];
    
    self.micVolSliderView = [YYNameSilderView view];
    @weakify(self);
    self.micVolSliderView.sliderValueChangedBlock = ^(id value) {
        @strongify(self);
        [self micVolValueChanged:value];
    };
    [self.micVolSliderView reloadName:BILocalizedString(@"home_mic_vol")];
    [self.volumeView addSubview:self.micVolSliderView];
    
    self.monitorVolSliderView = [YYNameSilderView view];
    self.monitorVolSliderView.sliderValueChangedBlock = ^(id value) {
        @strongify(self);
        [self monitorVolValueChanged:value];
    };
    [self.monitorVolSliderView reloadName:BILocalizedString(@"home_monitor_vol")];
    [self.volumeView addSubview:self.monitorVolSliderView];
    
    self.reverbVolSliderView = [YYNameSilderView view];
    self.reverbVolSliderView.sliderValueChangedBlock = ^(id value) {
        @strongify(self);
        [self reverbVolValueChanged:value];
    };
    [self.reverbVolSliderView reloadName:BILocalizedString(@"home_reverb_vol")];
    [self.volumeView addSubview:self.reverbVolSliderView];
    
    self.noiseReductionLevelSliderView = [YYNameSilderView view];
    self.noiseReductionLevelSliderView.sliderValueChangedBlock = ^(id value) {
        @strongify(self);
        [self noiseReductionLevelValueChanged:value];
    };
    [self.noiseReductionLevelSliderView setupMinValue:0 maxValue:4];
    [self.noiseReductionLevelSliderView reloadName:BILocalizedString(@"home_noise_reduction_level")];
    [self.volumeView addSubview:self.noiseReductionLevelSliderView];
    
    [self setupBassAndOther:@"home_straightness" imageName:@"straightness_unselected" button:self.straightnessButton label:self.straightnessLabel];
    [self setupBassAndOther:@"home_bass" imageName:@"bass_unselected" button:self.bassButton label:self.bassLabel];
    [self setupBassAndOther:@"home_baritone" imageName:@"baritone_unselected" button:self.baritoneButton label:self.baritoneLabel];
    [self setupBassAndOther:@"home_treble" imageName:@"treble_unselected" button:self.trebleButton label:self.trebleLabel];
}

- (void)setupSoundView {
    BIWaterfallLayout *layout = [BIWaterfallLayout new];
    layout.delegate = self;
    layout.columnCount = 4;
    layout.rowSpacing = 20.0;
    layout.columnSpacing = 12.0;
    
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.scrollEnabled = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"YYSoundCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:NSStringFromClass([YYSoundCell class])];
    [self.collectionView reloadData];
}

- (void)setupOther {
    self.otherView.layer.masksToBounds = YES;
    self.otherView.layer.cornerRadius = 16;
    self.otherView.backgroundColor = [UIColor whiteColor];
    
    self.dodgeLabel.text = BILocalizedString(@"home_dodge");
    self.dodgeLabel.textColor = [UIColor loadColorFromString:@"#333333"];
    self.dodgeLabel.font = BIFont(16);
    [self.dodgeButton setBackgroundImage:[UIImage imageNamed:@"home_switch_off"] forState:UIControlStateNormal];

    self.audioModeLabel.text = BILocalizedString(@"home_audio_mode");
    self.audioModeLabel.textColor = [UIColor loadColorFromString:@"#333333"];
    self.audioModeLabel.font = BIFont(16);
}

- (void)setupBassAndOther:(NSString *)text
                imageName:(NSString *)imageName
                   button:(UIButton *)button
                    label:(UILabel *)label {
    [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    label.text = BILocalizedString(text);
    label.textColor = [UIColor loadColorFromString:@"#333333"];
    label.font = BIFont(14);
}

- (void)setupLayout {
    [self.deviceConnectedView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    [self.deviceOtherStateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    [self.micVolSliderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(24);
    }];
    
    [self.monitorVolSliderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.micVolSliderView.mas_bottom).mas_equalTo(20);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(24);
    }];
    
    [self.reverbVolSliderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.monitorVolSliderView.mas_bottom).mas_equalTo(20);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(24);
    }];
    
    [self.noiseReductionLevelSliderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.reverbVolSliderView.mas_bottom).mas_equalTo(20);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(24);
    }];
}

#pragma mark - Public Method

- (void)reloadBleModel:(BIBluetoothModel *)bleModel {
    [self.deviceOtherStateView reloadDeviceState:bleModel.state];
    [self.deviceConnectedView reloadDeviceState:bleModel.state];
    [self.deviceConnectedView reloadDeviceName:bleModel.name];
    [self.deviceConnectedView reloadRecevierBattery:bleModel.deviceModel.recevierBattery];
    [self.deviceConnectedView reloadMicFirstBattery:bleModel.deviceModel.microphoneFirstBattery];
    [self.deviceConnectedView reloadMicSecondBattery:bleModel.deviceModel.microphoneSecondBattery];
    
    [self.micVolSliderView reloadProgress:bleModel.deviceModel.micVol];
    [self.monitorVolSliderView reloadProgress:bleModel.deviceModel.monitorVol];
    [self.reverbVolSliderView reloadProgress:bleModel.deviceModel.reverbVol];
    [self.noiseReductionLevelSliderView reloadProgress:bleModel.deviceModel.noiseReductionLevel];
    [self switchTimbreButton:bleModel.deviceModel.timbreType];
    [self.collectionView reloadData];
    
    if (bleModel.deviceModel.doggeOpen) {
        [self.dodgeButton setBackgroundImage:[UIImage imageNamed:@"home_switch_on"] forState:UIControlStateNormal];
    } else {
        [self.dodgeButton setBackgroundImage:[UIImage imageNamed:@"home_switch_off"] forState:UIControlStateNormal];
    }
    
    if (bleModel.deviceModel.audioModeOpen) {
        [self.audioModeButton setBackgroundImage:[UIImage imageNamed:@"home_switch_on"] forState:UIControlStateNormal];
    } else {
        [self.audioModeButton setBackgroundImage:[UIImage imageNamed:@"home_switch_off"] forState:UIControlStateNormal];
    }
}

- (void)reloadHomeModel:(YYHomeModel *)homeModel {
    self.homeModel = homeModel;
    [self.collectionView reloadData];
}

- (void)reloadUIWithLanguageChanged {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    [self.deviceOtherStateView reloadDeviceState:model.state];
    [self.deviceConnectedView reloadUIWithLanguageChanged];
    
    [self.micVolSliderView reloadName:BILocalizedString(@"home_mic_vol")];
    [self.monitorVolSliderView reloadName:BILocalizedString(@"home_monitor_vol")];
    [self.reverbVolSliderView reloadName:BILocalizedString(@"home_reverb_vol")];
    [self.noiseReductionLevelSliderView reloadName:BILocalizedString(@"home_noise_reduction_level")];

    [self setupBassAndOther:@"home_straightness" imageName:@"straightness_unselected" button:self.straightnessButton label:self.straightnessLabel];
    [self setupBassAndOther:@"home_bass" imageName:@"bass_unselected" button:self.bassButton label:self.bassLabel];
    [self setupBassAndOther:@"home_baritone" imageName:@"baritone_unselected" button:self.baritoneButton label:self.baritoneLabel];
    [self setupBassAndOther:@"home_treble" imageName:@"treble_unselected" button:self.trebleButton label:self.trebleLabel];
    
    [self.collectionView reloadData];
    
    self.dodgeLabel.text = BILocalizedString(@"home_dodge");
    self.audioModeLabel.text = BILocalizedString(@"home_audio_mode");
}

#pragma mark - Private Method

- (BOOL)checkIsConnected:(BIBluetoothModel *)model {
    if (model.state == kBIBluetoothConnected) {
        return YES;
    } else {
        [self showTextHUDWithTitle:BILocalizedString(@"hud_not_connect") afterDelay:1.0 completionBlock:nil];
        return NO;
    }
}

- (void)switchTimbreButton:(BITimbreType)timbreType {
    if (timbreType == kBITimbreStraightnessType) {
        [self.straightnessButton setBackgroundImage:[UIImage imageNamed:@"straightness_selected"] forState:UIControlStateNormal];
        [self.bassButton setBackgroundImage:[UIImage imageNamed:@"bass_unselected"] forState:UIControlStateNormal];
        [self.baritoneButton setBackgroundImage:[UIImage imageNamed:@"baritone_unselected"] forState:UIControlStateNormal];
        [self.trebleButton setBackgroundImage:[UIImage imageNamed:@"treble_unselected"] forState:UIControlStateNormal];
    } else if (timbreType == kBITimbreBassType) {
        [self.straightnessButton setBackgroundImage:[UIImage imageNamed:@"straightness_unselected"] forState:UIControlStateNormal];
        [self.bassButton setBackgroundImage:[UIImage imageNamed:@"bass_selected"] forState:UIControlStateNormal];
        [self.baritoneButton setBackgroundImage:[UIImage imageNamed:@"baritone_unselected"] forState:UIControlStateNormal];
        [self.trebleButton setBackgroundImage:[UIImage imageNamed:@"treble_unselected"] forState:UIControlStateNormal];
    } else if (timbreType == kBITimbreBaritoneType) {
        [self.straightnessButton setBackgroundImage:[UIImage imageNamed:@"straightness_unselected"] forState:UIControlStateNormal];
        [self.bassButton setBackgroundImage:[UIImage imageNamed:@"bass_unselected"] forState:UIControlStateNormal];
        [self.baritoneButton setBackgroundImage:[UIImage imageNamed:@"baritone_selected"] forState:UIControlStateNormal];
        [self.trebleButton setBackgroundImage:[UIImage imageNamed:@"treble_unselected"] forState:UIControlStateNormal];
    } else {
        [self.straightnessButton setBackgroundImage:[UIImage imageNamed:@"straightness_unselected"] forState:UIControlStateNormal];
        [self.bassButton setBackgroundImage:[UIImage imageNamed:@"bass_unselected"] forState:UIControlStateNormal];
        [self.baritoneButton setBackgroundImage:[UIImage imageNamed:@"bass_unselected"] forState:UIControlStateNormal];
        [self.trebleButton setBackgroundImage:[UIImage imageNamed:@"baritone_selected"] forState:UIControlStateNormal];
    }
}

#pragma mark - LYWaterfallLayoutDelegate

- (CGFloat)waterfallLayout:(BIWaterfallLayout *)waterfallLayout itemWidth:(CGFloat)itemWidth indexPath:(NSIndexPath *)indexPath {
    return 40.0;
}

#pragma mark - UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.homeModel.soundNameArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YYSoundCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([YYSoundCell class]) forIndexPath:indexPath];
    NSString *name = [self.homeModel.soundNameArray safeObjectAtIndex:indexPath.row];
    [cell setupName:name];
    
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if (model.deviceModel.soundType == indexPath.row) {
        [cell reloadSelected:YES];
    } else {
        [cell reloadSelected:NO];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        model.deviceModel.soundType = indexPath.row;
        NSData *data = [model.cmdModel setMicrophoneMode:indexPath.row];
        [[BIBluetoothManager sharedInstance] sendData:data model:model];
        [self reloadHomeModel:self.homeModel];
        [collectionView reloadData];
    }
}

#pragma mark - Action

- (void)micVolValueChanged:(id)value {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        NSUInteger micVol = [value unsignedIntegerValue];
        model.deviceModel.micVol = micVol;
        NSData *cmdData = [model.cmdModel setMicVol:micVol];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
    } else {
        [self.micVolSliderView reloadProgress:0];
    }
}

- (void)monitorVolValueChanged:(id)value {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        NSUInteger tempValue = [value unsignedIntegerValue];
        model.deviceModel.monitorVol = tempValue;
        NSData *cmdData = [model.cmdModel setMonitorVol:tempValue];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
    } else {
        [self.monitorVolSliderView reloadProgress:0];
    }
}

- (void)reverbVolValueChanged:(id)value {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        NSUInteger tempValue = [value unsignedIntegerValue];
        model.deviceModel.reverbVol = tempValue;
        NSData *cmdData = [model.cmdModel setReverberation:tempValue];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
    } else {
        [self.reverbVolSliderView reloadProgress:0];
    }
}

- (void)noiseReductionLevelValueChanged:(id)value {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        NSUInteger tempValue = [value unsignedIntegerValue];
        model.deviceModel.noiseReductionLevel = tempValue;
        NSData *cmdData = [model.cmdModel setNoiseReductionLevel:tempValue];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
    } else {
        [self.noiseReductionLevelSliderView reloadProgress:0];
    }
}

- (IBAction)clickStraightnessButton:(id)sender {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        model.deviceModel.timbreType = kBITimbreStraightnessType;
        [self switchTimbreButton:kBITimbreStraightnessType];
        NSData *cmdData = [model.cmdModel setToneControl:kBITimbreStraightnessType];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
    }
}

- (IBAction)clickBassButton:(id)sender {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        model.deviceModel.timbreType = kBITimbreBassType;
        [self switchTimbreButton:kBITimbreBassType];
        NSData *cmdData = [model.cmdModel setToneControl:kBITimbreBassType];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
    }
}

- (IBAction)clickBaritoneButton:(id)sender {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        model.deviceModel.timbreType = kBITimbreBaritoneType;
        [self switchTimbreButton:kBITimbreBaritoneType];
        NSData *cmdData = [model.cmdModel setToneControl:kBITimbreBaritoneType];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
    }
}

- (IBAction)clickTrebleButton:(id)sender {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        model.deviceModel.timbreType = kBITimbreTrebleType;
        [self switchTimbreButton:kBITimbreTrebleType];
        NSData *cmdData = [model.cmdModel setToneControl:kBITimbreTrebleType];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
    }
}

- (IBAction)clickDodgeSwitch:(UIButton *)sender {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        BOOL newValue = !model.deviceModel.doggeOpen;
        model.deviceModel.doggeOpen = newValue;
        NSData *cmdData = [model.cmdModel setDodge:newValue];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
        if (newValue) {
            [self.dodgeButton setBackgroundImage:[UIImage imageNamed:@"home_switch_on"] forState:UIControlStateNormal];
        } else {
            [self.dodgeButton setBackgroundImage:[UIImage imageNamed:@"home_switch_off"] forState:UIControlStateNormal];
        }
    }
}

- (IBAction)clickAudioModeSwitch:(UIButton *)sender {
    BIBluetoothModel *model = [BIBluetoothManager sharedInstance].currentBluetoothModel;
    if ([self checkIsConnected:model]) {
        BOOL newValue = !model.deviceModel.audioModeOpen;
        model.deviceModel.audioModeOpen = newValue;
        NSData *cmdData = [model.cmdModel setCancellingOriginalSound:newValue];
        [[BIBluetoothManager sharedInstance] sendData:cmdData model:model];
        
        if (newValue) {
            [self.audioModeButton setBackgroundImage:[UIImage imageNamed:@"home_switch_on"] forState:UIControlStateNormal];
        } else {
            [self.audioModeButton setBackgroundImage:[UIImage imageNamed:@"home_switch_off"] forState:UIControlStateNormal];
        }
    }
}

@end
